﻿'use strict';

exports = module.exports;

function hasCycleDFS(blocks, current, visited, inStack) {
    visited.add(current);
    inStack.add(current);

    for (let output of blocks[current].outputs) {
        if (!visited.has(output)) {
            if (hasCycleDFS(blocks, output, visited, inStack)) {
                return true;
            }
        } else if (inStack.has(output)) {
            console.log("Cycle detected!");
            return true;
        }
    }

    inStack.delete(current);
    return false;
}

exports.detectCycleDFS = function(blocks) {
    let visited = new Set();
    let inStack = new Set();

    for (let block of blocks) {
        if (!visited.has(block.id)) {
            if (hasCycleDFS(blocks, block.id, visited, inStack)) {
                return true; // Cycle detected
            }
        }
    }

    return false; // No cycle detected
}

exports.topologicalSort = function(blocks) {
    let result = [];
    let visited = new Set();

    function dfs(current) {
        visited.add(current);

        for (let output of blocks[current].outputs) {
            if (!visited.has(output)) {
                dfs(output);
            }
        }

        result.push(current);
    }

    for (let block of blocks) {
        if (!visited.has(block.id)) {
            dfs(block.id);
        }
    }

    return result.reverse(); // Reverse to get the topological order
}
